<template>
  <div class="block-config-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h1 class="page-title">区块设置</h1>
        <p class="page-desc">配置区块类型、字段结构和显示模板</p>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="handleAdd" icon="Plus">
          新建区块类型
        </el-button>
      </div>
    </div>

    <!-- 搜索区域 -->
    <div class="search-section">
      <el-form :model="searchForm" inline>
        <el-form-item label="区块名称">
          <el-input v-model="searchForm.name" placeholder="请输入区块名称" clearable />
        </el-form-item>
        <el-form-item label="区块类型">
          <el-select v-model="searchForm.type" placeholder="请选择类型" clearable>
            <el-option label="轮播图" value="carousel" />
            <el-option label="文章列表" value="article_list" />
            <el-option label="友情链接" value="links" />
            <el-option label="自定义内容" value="custom" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getBlockConfigList" icon="Search">搜索</el-button>
          <el-button @click="resetSearch" icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 区块配置列表 -->
    <div class="config-table">
      <el-table :data="configList" v-loading="loading" stripe>
        <el-table-column prop="name" label="区块名称" min-width="150" />
        <el-table-column prop="code" label="区块代码" width="120" />
        <el-table-column prop="type" label="类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getTypeTagType(row.type)">
              {{ getTypeText(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="maxItems" label="最大条目数" width="100" align="center" />
        <el-table-column prop="template" label="模板" width="120" />
        <el-table-column prop="status" label="状态" width="80" align="center">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="createDate" label="创建时间" width="160" />
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" text @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="success" size="small" text @click="handleFields(row)">
              字段配置
            </el-button>
            <el-button type="info" size="small" text @click="goToFieldConfig(row)">
              详细配置
            </el-button>
            <el-button type="danger" size="small" text @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="getBlockConfigList"
          @current-change="getBlockConfigList"
        />
      </div>
    </div>

    <!-- 区块配置编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="formRules"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="区块名称" prop="name">
              <el-input
                v-model="form.name"
                placeholder="请输入区块名称"
                @input="handleNameChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="区块代码">
              <el-input
                v-model="form.code"
                placeholder="自动生成"
                readonly
                style="background-color: #f5f7fa;"
              />
              <div class="el-form-item__tip">根据区块名称自动生成，用于模板调用</div>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="区块类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择类型">
                <el-option label="轮播图" value="carousel" />
                <el-option label="文章列表" value="article_list" />
                <el-option label="友情链接" value="links" />
                <el-option label="自定义内容" value="custom" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最大条目数" prop="maxItems">
              <el-input-number v-model="form.maxItems" :min="1" :max="100" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入区块描述"
          />
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="显示模板" prop="template">
              <el-select v-model="form.template" placeholder="请选择模板">
                <el-option label="默认模板" value="default" />
                <el-option label="卡片模板" value="card" />
                <el-option label="列表模板" value="list" />
                <el-option label="网格模板" value="grid" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio :label="1">启用</el-radio>
                <el-radio :label="0">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 字段配置对话框 -->
    <el-dialog
      v-model="fieldsDialogVisible"
      title="字段配置"
      width="1000px"
    >
      <div class="fields-config" v-loading="fieldsLoading">
        <div class="fields-header">
          <el-button type="primary" @click="addField" icon="Plus">添加字段</el-button>
        </div>

        <div v-if="currentFields.length === 0 && !fieldsLoading" style="text-align: center; padding: 40px;">
          <el-empty description="暂无字段配置" />
        </div>

        <el-table v-else :data="currentFields" stripe>
          <el-table-column prop="name" label="字段名" width="140">
            <template #default="{ row, $index }">
              <el-input v-model="row.name" placeholder="字段名称" size="small" />
            </template>
          </el-table-column>
          <el-table-column prop="label" label="字段标签" width="140">
            <template #default="{ row, $index }">
              <el-input v-model="row.label" placeholder="字段标签" size="small" />
            </template>
          </el-table-column>
          <el-table-column prop="type" label="字段类型" width="120">
            <template #default="{ row }">
              <el-select v-model="row.type" size="small" placeholder="选择类型">
                <el-option label="文本" value="text" />
                <el-option label="数字" value="number" />
                <el-option label="多行文本" value="textarea" />
                <el-option label="选择框" value="select" />
                <el-option label="单选框" value="radio" />
                <el-option label="复选框" value="checkbox" />
                <el-option label="图片" value="image" />
                <el-option label="文件" value="file" />
                <el-option label="日期" value="date" />
                <el-option label="时间" value="datetime" />
                <el-option label="链接" value="url" />
                <el-option label="富文本" value="editor" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="required" label="必填" width="80" align="center">
            <template #default="{ row }">
              <el-switch v-model="row.required" size="small" />
            </template>
          </el-table-column>
          <el-table-column prop="placeholder" label="占位符" width="150">
            <template #default="{ row }">
              <el-input v-model="row.placeholder" size="small" placeholder="占位符" />
            </template>
          </el-table-column>
          <el-table-column prop="description" label="描述" min-width="120">
            <template #default="{ row }">
              <el-input v-model="row.description" size="small" placeholder="字段描述" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100" align="center">
            <template #default="{ row, $index }">
              <el-button type="danger" size="small" text @click="removeField($index)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <template #footer>
        <el-button @click="fieldsDialogVisible = false" :disabled="submitting">取消</el-button>
        <el-button type="primary" @click="saveFields" :loading="submitting">保存字段配置</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Plus, Search, Refresh } from '@element-plus/icons-vue'
import { blockApi } from '@/api/block'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const fieldsDialogVisible = ref(false)
const fieldsLoading = ref(false)
const submitting = ref(false)
const isEdit = ref(false)
const formRef = ref<FormInstance>()

// 搜索表单
const searchForm = ref({
  name: '',
  type: '',
  status: undefined
})

// 分页信息
const pagination = ref({
  page: 1,
  size: 20,
  total: 0
})

// 配置列表
const configList = ref([])

// 当前编辑的字段配置
const currentFields = ref([])
const currentConfigId = ref(null)

// 表单数据
const form = ref({
  name: '',
  code: '',
  type: '',
  description: '',
  maxItems: 10,
  template: 'default',
  status: 1
})

// 表单验证规则
const formRules: FormRules = {
  name: [
    { required: true, message: '请输入区块名称', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择区块类型', trigger: 'change' }
  ]
}

// 对话框标题
const dialogTitle = computed(() => isEdit.value ? '编辑区块配置' : '新建区块配置')

// 获取配置列表
const getBlockConfigList = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.value.page,
      size: pagination.value.size,
      name: searchForm.value.name,
      type: searchForm.value.type,
      status: searchForm.value.status
    }

    const response = await blockApi.getConfigList(params)
    if (response.code === 0) {
      configList.value = response.data.list || []
      pagination.value.total = response.data.total || 0
    } else {
      ElMessage.error(response.msg || '获取配置列表失败')
    }
  } catch (error) {
    console.error('获取配置列表失败:', error)
    ElMessage.error('获取配置列表失败')
  } finally {
    loading.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    name: '',
    type: '',
    status: undefined
  }
  getBlockConfigList()
}

// 改进的别名生成工具
class AliasGenerator {
  // 扩展的中文到英文映射表
  private static readonly WORD_MAP: Record<string, string> = {
    // 位置相关
    '顶部': 'top',
    '底部': 'footer',
    '头部': 'header',
    '尾部': 'footer',
    '左侧': 'left',
    '右侧': 'right',
    '中间': 'center',
    '侧边': 'sidebar',
    '主要': 'main',
    '次要': 'secondary',

    // 功能相关
    '菜单': 'menu',
    '导航': 'nav',
    '链接': 'link',
    '按钮': 'button',
    '搜索': 'search',
    '登录': 'login',
    '注册': 'register',
    '用户': 'user',
    '个人': 'profile',
    '设置': 'settings',

    // 内容相关
    '新闻': 'news',
    '文章': 'article',
    '博客': 'blog',
    '公告': 'announcement',
    '通知': 'notice',
    '活动': 'activity',
    '事件': 'event',
    '讨论': 'discussion',
    '评论': 'comment',
    '留言': 'message',
    '反馈': 'feedback',

    // 媒体相关
    '图片': 'image',
    '照片': 'photo',
    '视频': 'video',
    '音频': 'audio',
    '文件': 'file',
    '下载': 'download',
    '上传': 'upload',
    '轮播': 'carousel',
    '幻灯片': 'slider',
    '画廊': 'gallery',

    // 组织相关
    '关于': 'about',
    '联系': 'contact',
    '团队': 'team',
    '成员': 'member',
    '合作': 'partner',
    '客户': 'client',
    '服务': 'service',
    '产品': 'product',
    '项目': 'project',

    // 页面相关
    '首页': 'home',
    '主页': 'index',
    '列表': 'list',
    '详情': 'detail',
    '内容': 'content',
    '页面': 'page',
    '栏目': 'category',
    '分类': 'category',
    '标签': 'tag',

    // 其他常用
    '最新': 'latest',
    '热门': 'hot',
    '推荐': 'featured',
    '精选': 'selected',
    '更多': 'more',
    '全部': 'all',
    '友情': 'friend',
    '征集': 'collection',
    '会议': 'conference',
    '展示': 'showcase',
    '介绍': 'intro'
  }

  // 生成别名的主方法
  static generate(name: string, existingAliases: string[] = []): string {
    if (!name || !name.trim()) {
      return this.generateTimestampAlias()
    }

    // 清理输入
    const cleanName = this.cleanInput(name)

    // 转换为英文
    let alias = this.convertToEnglish(cleanName)

    // 格式化
    alias = this.formatAlias(alias)

    // 确保唯一性
    alias = this.ensureUnique(alias, existingAliases)

    return alias
  }

  // 清理输入字符串
  private static cleanInput(name: string): string {
    return name
      .trim()
      .replace(/[^\u4e00-\u9fa5a-zA-Z0-9\s]/g, '') // 移除特殊字符，保留空格
      .replace(/\s+/g, ' ') // 合并多个空格
  }

  // 转换为英文
  private static convertToEnglish(name: string): string {
    let result = name

    // 按长度排序，优先匹配长词汇
    const sortedEntries = Object.entries(this.WORD_MAP)
      .sort(([a], [b]) => b.length - a.length)

    // 替换中文词汇
    for (const [chinese, english] of sortedEntries) {
      const regex = new RegExp(chinese, 'g')
      result = result.replace(regex, ` ${english} `)
    }

    // 处理剩余的中文字符
    if (/[\u4e00-\u9fa5]/.test(result)) {
      // 如果还有中文，可以考虑集成拼音库
      // 这里暂时使用简单的处理方式
      result = result.replace(/[\u4e00-\u9fa5]/g, 'block')
    }

    return result
  }

  // 格式化别名
  private static formatAlias(alias: string): string {
    return alias
      .toLowerCase()
      .trim()
      .replace(/\s+/g, '_') // 空格转下划线
      .replace(/[^a-z0-9_]/g, '') // 移除非法字符
      .replace(/_+/g, '_') // 合并多个下划线
      .replace(/^_|_$/g, '') // 移除首尾下划线
      .substring(0, 50) // 限制长度
      .replace(/_$/, '') // 再次移除尾部下划线
  }

  // 确保别名以字母开头
  private static ensureValidStart(alias: string): string {
    if (!/^[a-z]/.test(alias)) {
      return `block_${alias}`
    }
    return alias
  }

  // 确保唯一性
  private static ensureUnique(alias: string, existingAliases: string[]): string {
    alias = this.ensureValidStart(alias)

    if (!existingAliases.includes(alias)) {
      return alias
    }

    // 如果重复，添加数字后缀
    let counter = 1
    let uniqueAlias = `${alias}_${counter}`

    while (existingAliases.includes(uniqueAlias)) {
      counter++
      uniqueAlias = `${alias}_${counter}`
    }

    return uniqueAlias
  }

  // 生成基于时间戳的别名
  private static generateTimestampAlias(): string {
    return `block_${Date.now()}`
  }
}

// 根据名称生成代码
const generateCode = (name: string): string => {
  // 获取现有的别名列表
  const existingAliases = blockConfigs.value.map(config => config.code).filter(Boolean)

  return AliasGenerator.generate(name, existingAliases)
}

// 处理名称变化
const handleNameChange = (name: string) => {
  if (!isEdit.value) {
    form.value.code = generateCode(name)
  }
}

// 处理新增
const handleAdd = () => {
  isEdit.value = false
  dialogVisible.value = true
}

// 处理编辑
const handleEdit = (row: any) => {
  isEdit.value = true
  form.value = { ...row }
  dialogVisible.value = true
}

// 处理字段配置
const handleFields = async (row: any) => {
  currentConfigId.value = row.id
  fieldsLoading.value = true

  try {
    console.log('加载区块字段配置:', row.id)
    const response = await blockApi.getFields(row.id)
    console.log('字段配置响应:', response)

    if (response.code === 0) {
      currentFields.value = (response.data || []).map((field: any) => ({
        ...field,
        options: field.options ? JSON.parse(field.options) : [],
        // 转换整数为布尔值，符合前端期望
        required: field.required === 1,
        status: field.status === 1
      }))
      console.log('加载的字段配置:', currentFields.value)

      // 如果没有字段配置，根据区块类型初始化默认字段
      if (currentFields.value.length === 0 && row.type) {
        await initDefaultFieldsForBlock(row.type, row.id)
      }
    } else {
      ElMessage.error(response.msg || '获取字段配置失败')
      currentFields.value = []
    }
  } catch (error) {
    console.error('获取字段配置失败:', error)
    ElMessage.error('获取字段配置失败')
    currentFields.value = []
  } finally {
    fieldsLoading.value = false
  }

  fieldsDialogVisible.value = true
}

// 跳转到详细字段配置页面
const goToFieldConfig = (row: any) => {
  router.push(`/content/block/field-config?blockId=${row.id}`)
}

// 根据区块类型初始化默认字段
const initDefaultFieldsForBlock = async (blockType: string, blockId: number) => {
  try {
    console.log('初始化默认字段，区块类型:', blockType, '区块ID:', blockId)
    const response = await blockApi.getDefaultFields(blockType)
    console.log('默认字段响应:', response)

    if (response.code === 0 && response.data && response.data.length > 0) {
      currentFields.value = response.data.map((field: any, index: number) => ({
        ...field,
        id: `default_${Date.now()}_${index}`,
        options: field.options ? JSON.parse(field.options) : [],
        // 转换整数为布尔值，符合前端期望
        required: field.required === 1,
        status: field.status === 1
      }))

      // 自动保存默认字段
      await saveFieldsToDatabase()
      ElMessage.success(`已为${getBlockTypeLabel(blockType)}类型区块初始化默认字段`)
    }
  } catch (error) {
    console.error('初始化默认字段失败:', error)
  }
}

// 获取区块类型标签
const getBlockTypeLabel = (type: string) => {
  const typeMap: Record<string, string> = {
    'carousel': '轮播图',
    'article_list': '文章列表',
    'news': '新闻',
    'activity': '活动',
    'discussion': '讨论',
    'image': '图片',
    'text': '文本',
    'html': 'HTML',
    'video': '视频',
    'list': '列表',
    'custom': '自定义'
  }
  return typeMap[type] || type
}

// 添加字段
const addField = () => {
  const newField = {
    id: `new_${Date.now()}_${currentFields.value.length}`,
    name: `field_${currentFields.value.length + 1}`,
    label: `字段${currentFields.value.length + 1}`,
    type: 'text',
    description: '',
    defaultValue: '',
    placeholder: '',
    required: false,
    options: [],
    orderNum: currentFields.value.length + 1,
    status: 1
  }

  currentFields.value.push(newField)
}

// 删除字段
const removeField = (index: number) => {
  currentFields.value.splice(index, 1)
}

// 保存字段配置到数据库
const saveFieldsToDatabase = async () => {
  const fieldsData = currentFields.value.map(field => {
    const fieldData = {
      ...field,
      options: field.options && field.options.length > 0 ? JSON.stringify(field.options) : null,
      // 转换布尔值为整数，符合后端期望
      required: field.required ? 1 : 0,
      status: field.status ? 1 : 0
    }

    // 删除所有ID，让后端重新生成，避免主键冲突
    delete fieldData.id

    return fieldData
  })

  console.log('保存字段数据到后端:', {
    blockId: currentConfigId.value,
    fieldsCount: fieldsData.length,
    fields: fieldsData
  })

  const response = await blockApi.saveFields(currentConfigId.value, fieldsData)
  console.log('字段保存响应:', response)

  if (response.code === 0) {
    return true
  } else {
    throw new Error(response.msg || '保存失败')
  }
}

// 保存字段配置
const saveFields = async () => {
  try {
    submitting.value = true
    await saveFieldsToDatabase()
    ElMessage.success('字段配置保存成功')
    fieldsDialogVisible.value = false
  } catch (error) {
    console.error('保存字段配置失败:', error)
    ElMessage.error('保存字段配置失败: ' + (error.message || '未知错误'))
  } finally {
    submitting.value = false
  }
}

// 处理删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm(`确定要删除区块配置"${row.name}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      const response = await blockApi.deleteConfig(row.id)
      if (response.code === 0) {
        ElMessage.success('删除成功')
        getBlockConfigList()
      } else {
        ElMessage.error(response.msg || '删除失败')
      }
    } catch (error) {
      console.error('删除配置失败:', error)
      ElMessage.error('删除失败')
    }
  })
}

// 处理状态变更
const handleStatusChange = async (row: any) => {
  try {
    const response = await blockApi.updateConfigStatus(row.id, row.status)
    if (response.code === 0) {
      ElMessage.success('状态更新成功')
    } else {
      ElMessage.error(response.msg || '状态更新失败')
      // 恢复原状态
      row.status = row.status === 1 ? 0 : 1
    }
  } catch (error) {
    console.error('更新状态失败:', error)
    ElMessage.error('状态更新失败')
    // 恢复原状态
    row.status = row.status === 1 ? 0 : 1
  }
}

// 处理提交
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    submitting.value = true

    const response = isEdit.value
      ? await blockApi.updateConfig(form.value)
      : await blockApi.createConfig(form.value)

    if (response.code === 0) {
      ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
      dialogVisible.value = false
      getBlockConfigList()
    } else {
      ElMessage.error(response.msg || '操作失败')
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('操作失败')
  } finally {
    submitting.value = false
  }
}

// 重置表单
const resetForm = () => {
  isEdit.value = false
  form.value = {
    name: '',
    code: '',
    type: '',
    description: '',
    maxItems: 10,
    template: 'default',
    status: 1
  }
  formRef.value?.resetFields()
}

// 获取类型标签类型
const getTypeTagType = (type: string) => {
  const typeMap: Record<string, string> = {
    carousel: 'primary',
    article_list: 'success',
    links: 'warning',
    custom: 'info'
  }
  return typeMap[type] || 'info'
}

// 获取类型文本
const getTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    carousel: '轮播图',
    article_list: '文章列表',
    links: '友情链接',
    custom: '自定义内容'
  }
  return typeMap[type] || '未知'
}

onMounted(() => {
  getBlockConfigList()
})
</script>

<style scoped lang="scss">
.block-config-management {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 60px);

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 20px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);

    .header-left {
      .page-title {
        font-size: 20px;
        font-weight: 600;
        color: #303133;
        margin: 0 0 4px 0;
      }

      .page-desc {
        font-size: 13px;
        color: #909399;
        margin: 0;
      }
    }
  }

  .search-section {
    background: white;
    padding: 20px;
    border-radius: 8px;
    margin-bottom: 20px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  }

  .config-table {
    background: white;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);

    .pagination {
      margin-top: 20px;
      text-align: right;
    }
  }

  .fields-config {
    .fields-header {
      margin-bottom: 16px;
    }
  }
}
</style>
